package com.yn.xgame.logic;

import com.alibaba.fastjson.JSON;
import com.yn.xgame.game.message.SimplePlayer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yn.xgame.IFuncServerLike;
import com.yn.xgame.ThreadServer;
import com.yn.xgame.logic.util.CheckUtils;
import com.yn.xgame.logic.util.GenUtils;
import com.yn.xgame.logic.util.JedisUtils;
import com.yn.xgame.logic.util.SendMsgUtil;
import com.yn.xgame.message.C2GPbRedirectMessage;
import redis.clients.jedis.Jedis;

public class AssistServer extends ThreadServer implements IFuncServerLike {


	private static final String KEY_SIMPLE_PLAYER = "sp";

	private Logger logger=LoggerFactory.getLogger(AssistServer.class);
	
	private Jedis jedis;
	private static String CAPTCHA_USER_MAP = "cap";
	
	public AssistServer() {
		super("AssistServer");
	}
	
	public int captcha(C2GPbRedirectMessage msg, GamePlayer player){
		String captcha=msg.getPb().getCaptchaReq().getCaptcha();
		int result;
		if(StringUtils.isBlank(captcha)){
			result=sendCaptcha(String.valueOf(player.getUserId()),player.getUserTel());
		}else{
			result=verifyCaptcha(String.valueOf(player.getUserId()),player.getUserTel());
		}
		return result;
	}
	
	public int sendCaptcha(String id,String phoneNo){
		if(!CheckUtils.checkMobilePhoneNo(phoneNo)){
			return 3;
		}
		String genCaptcha=GenUtils.genCaptcha();
		try{
			SendMsgUtil.sendMsg(genCaptcha,"39550",phoneNo);
		}catch(Exception e){
			logger.error(e.getMessage());
			return 5;
		}
		try{
			jedis=JedisUtils.getJedis();
			jedis.hset(CAPTCHA_USER_MAP, id, genCaptcha);
			jedis.expire(id, 60);
		}catch(Exception e){
			logger.error(e.getMessage());
			return 6;
		}
		return 1;
	}
	
	public int verifyCaptcha(String id, String captcha) {
		try{
			jedis=JedisUtils.getJedis();
			String original=jedis.hget(CAPTCHA_USER_MAP, id);
			if(original==null){
				return 2;
			}
			if(original.equalsIgnoreCase(captcha)){
				jedis.hdel(CAPTCHA_USER_MAP, id);
				return 1;
			}
			jedis.hdel(CAPTCHA_USER_MAP, id);
			return 0;
		}catch(Exception e){
			logger.error(e.getMessage());
			return 6;
		}
	}

	public void updateSimplePlayerInRedis(SimplePlayer player) {
		jedis = JedisUtils.getJedis();
		String str = JSON.toJSONString(player);
		jedis.hset(KEY_SIMPLE_PLAYER, Integer.toString(player.uid), str);
	}

	public void delSimplePlayerInRedis(int userId) {
		jedis.hdel(KEY_SIMPLE_PLAYER, Integer.toString(userId));
	}

}
